﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.QuanLyKho.ThongKeTonTheoNhaCungCap
{
    public partial class FrmTongHopTienHangTheoNhaCungCap : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopTienHangTheoNhaCungCap()
        {
            InitializeComponent();
        }

        private void FrmTongHopGiaTriTheoNhaCungCap_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView.ToTable());
                gridControlDsDoiTac.DataSource = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewTienTheoNCC.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }

            chkChooseAllDoiTac.Checked = true;
            FormatNumberInGridView(gridViewTienTheoNCC);
            FormatNumberInGridView(gridViewDsDoiTac);
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
       
        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
                {
                    row["Choose"] = chkChooseAllDoiTac.Checked;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            Guid khoID = Guid.Empty;
            if(cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty)
                khoID = (Guid)cmbKho.EditValue;

            BasicForms.FrmProgressBarDev.StartShowProgress("Đang xử lý");
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Clear();
                int count = 1;
                int total = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Select("Choose = 1").Length;

                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
                {
                    BasicForms.FrmProgressBarDev.Status = string.Format("Đã tính toán được {0} / {1} nhà cung cấp", count, total);

                    if (row["Choose"] is bool && (bool)row["Choose"])
                    {
                        Guid doiTuongNghiepVuID = (Guid)row["ID"];
                        DoiTuongNghiepVu doiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID(doiTuongNghiepVuID);
                        ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayBatDau);

                        TonKho phatSinhNhap = TonKho.CalculatePhatSinhNhapToanBoTheoNCC(cmd, ngayKetThuc, doiTuongNghiepVuID);
                        TonKho phatSinhXuat = TonKho.CalculatePhatSinhXuatBanHangTuNCC(cmd, ngayKetThuc, doiTuongNghiepVuID);
                        TonKho tonKho = TonKho.CalculateTongTonTatCaMatHangTheoNhaCungCap(cmd, ngayKetThuc, doiTuongNghiepVuID);
                        
                        DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.NewRow();
                        
                        addedRow["MaNCC"] = doiTuongNghiepVu.Ma;
                        addedRow["TenNCC"] = doiTuongNghiepVu.Ten;
                        addedRow["SoTienNhap"] = phatSinhNhap.ThanhTien;
                        addedRow["SoTienXuat"] = phatSinhXuat.ThanhTien;
                        addedRow["SoTienTon"] = tonKho.ThanhTien;

                        dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Rows.Add(addedRow);
                        count++;
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBarDev.FinishShowProgress();
            }

            gridControlTienTheoNCC.DataSource = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap;
            //AlphabeticSort(dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap, "TenNCC", 0).DefaultView; 
            FormatNumberInGridView(gridViewTienTheoNCC);
            FormatNumberInGridView(gridViewDsDoiTac);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(true, gridControlTienTheoNCC, true, true, "Thống kê tổng hợp tiền theo nhà cung cấp", "");
        }

        private DataTable AlphabeticSort(DataTable dtTable, string sortColumn, int sortOrder)
        {
            DataSet dsSorted = new DataSet();
            string columnKey = sortColumn;
            string sortDirection = "";
            string sortFormat = "{0} {1}";
            switch (sortOrder)
            {
                case 0:
                    sortDirection = "ASC";
                    break;
                case 1:
                    sortDirection = "DESC";
                    break;
                default:
                    sortDirection = "ASC";
                    break;
            }

            dtTable.DefaultView.Sort = string.Format(sortFormat, columnKey, sortDirection);

            return dtTable.DefaultView.Table;
        }

    }
}
